﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MKAdmin.ToolKit
{
    public class LinkUrlHelper
    {
        #region 验证链接地址是否有效
        /// <summary>
        /// 验证链接地址是否有效
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool LinkUrlVerify(string url, ref string title, ref string desc)
        {
            bool result = true;
            if (url == null)
            {
                return false;
            }
            string pattern = @"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?";

            Match match = Regex.Match(url.Trim(), pattern);
            result = match.Success;

            if (result)
            {
                try
                {
                    //string soundcode = client.DownloadString(url);
                    bool isVaildUrl = urlIsVaild(url.Trim(), ref title, ref desc);
                    if (!isVaildUrl)
                    {
                        result = false;
                    }
                }
                catch (Exception)
                {
                    result = false;
                }
            }

            return result;
        }
        private static bool urlIsVaild(string url, ref string title, ref string desc)
        {
            bool result = false;
            try
            {
                string soundcode = WebHelper.GetWebSourceCode(url);
                ////解析
                //Regex reg_charset = new Regex("<meta[^>]*?charset=(\\w+)[\\W]*?>", RegexOptions.IgnoreCase);
                //Match mc_charset = reg_charset.Match(soundcode);
                //if (mc_charset.Success)
                //{
                //    title = mc_charset.Groups["charset"].ToString();
                //}

                //解析title
                Regex reg_title = new Regex(@"<title>(?<title>[\s\S]+?)</title>", RegexOptions.IgnoreCase);
                Match mc_title = reg_title.Match(soundcode);
                if (mc_title.Success)
                {
                    title = mc_title.Groups["title"].Value;
                }

                //解析content
                Regex reg_desc = new Regex(@"<meta name=""(description|Description)"".*? content=""(?<content>.*?)""");
                Match mc_desc = reg_desc.Match(soundcode);
                if (mc_desc.Success)
                {
                    desc = mc_desc.Groups["content"].Value;
                }
                else
                {
                    desc = title;
                }

                if (soundcode != "URL解析失败")
                {
                    result = true;
                }
                else
                {
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                    myRequest.Method = "HEAD";　              //设置提交方式可以为＂ｇｅｔ＂，＂ｈｅａｄ＂等
                    myRequest.Timeout = 10000;　             //设置网页响应时间长度
                    myRequest.AllowAutoRedirect = true;//是否允许自动重定向
                    myRequest.UseDefaultCredentials = true;
                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                    result = (myResponse.StatusCode == HttpStatusCode.OK ||
                        myResponse.StatusCode == HttpStatusCode.NoContent);//返回响应的状态
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("链接验证失败:" + ex.Message);
                result = false;
            }

            return result;
        }
        #endregion
    }
}
